
/**
 * Created by wxnacy on 2015/8/12.
 */
$(function() {
    //console.log("initPlayAudio");
    //initPlayAudio();
    getUploadId($('#audioFile'));
    //replaceButton($('#replace'));
});

/**
 * 初始化播放视频的按钮
 */
function initPlayAudio(){
    //视频列表中的点击元素
    var $openAudio = $('button[data-target=".play-audio"]');
    console.log($openAudio);

    $openAudio.each(function(){
        console.log($(this));
        playAudio($(this));
    });

}

function playAudio($openAudio){
    $openAudio.click(function(){
        console.log($openAudio);
        var $this = $(this);
        var audioId = $this.attr('audio-id');
        $.get(URL_AUDIO_DETAIL+audioId,function(data,status){
            if(status == 'success'){
                var success = data.success;
                if(success){
                    var url = data.data.url;
                    var title = data.data.name;
                    var bigPic = data.data.bigPic;
                    var smallPic = data.data.smallPic;
                    var src = '/fmbox/index.html?title='+title+'&url='+url+'&pic='+bigPic;
                    $('#audio-iframe').attr('src',src);

                }else{
                    var msg = data.msg;// '直播类型暂不支持播放';
                    var type = 'error';
                    var $layout = 'topRight';
                    notyRestart(msg,type,$layout);
                }
            }
        });
    });
}


var audioHtml = $('#audioFile').clone(true).prop('outerHTML');
var playHtml = '<audio id="play" controls="controls" src=""/>';
/**
 * 点击更换的效果
 * @param $replace
 */
function replaceButton($replace){
    $replace.click(function(e){
        e.preventDefault();
        var $play = $('#play');
        if($play.length>0){
            var $audioFile = $('<input type="file" id="audioFile"/>');
            getUploadId($audioFile);
            $play.replaceWith($audioFile);
        }
    });
}

/**
 * 获取uploadId
 * @param $audioFile
 */
function getUploadId($audioFile){
    $audioFile.change(function(){
        var $this = $(this);
        console.log(this);
        var form = new FormData();
        var file = $this[0].files[0],  //文件对象
            name = file.name;        //文件名
        $.ajax({
            url: "/vrs/api/getUploadId.jsn?name="+name,
            type: "GET",
            async: true,        //异步
            processData: false,  //很重要，告诉jquery不要对form进行处理
            contentType: false,  //很重要，指定为false才能形成正确的Content-Type
            success: function (data) {

                var status = data.status;
                if(status == 1){
                    part.key = data.data.key;
                    part.uploadId = data.data.multipartUploadId;
//                                $.proxy($this.upload, $this)
                    var $text = $('[data-theme-name="upload-audio-text"]');
                    $text.text(0 + "%");
                    uploadMultipart(0,file);
                }
            }
        });
    });
}

//        var key,uploadId;
var part={
    key:"",uploadId:"",jobId:"",state:"",intervalId:0,audioUrl:""
};
/**
 * 分片上传音频
 * @param i
 * @param file
 */
function uploadMultipart (i,file) {
    i = parseInt(i);
//                var file = $("#file")[0].files[0],  //文件对象
//                        name = file.name,        //文件名
    var     size = file.size,        //总大小
        succeed = 0;
    var shardSize = 2 * 1024 * 1024,    //以2MB为一个分片
        shardCount = Math.ceil(size / shardSize);  //总片数
    if(i == shardCount){
        return;
    }
//                for (var i = 0; i < shardCount; ++i) {
//计算每一片的起始与结束位置
    var start = i * shardSize,
        end = Math.min(size, start + shardSize);
//构造一个表单，FormData是HTML5新增的
    var form = new FormData();
    form.append("data", file.slice(start, end));  //slice方法用于切出文件的一部分
//                    form.append("name", name);
    form.append("total", shardCount);  //总片数
    form.append("index", i + 1);        //当前是第几片
    //form.append("random", random);        //唯一标示，随机数
    form.append("key", part.key);        //文件最终路径
    form.append("uploadId", part.uploadId);        //uploadId唯一标示
//Ajax提交
    $.ajax({
        url: "/vrs/api/multipartUpload.jsn",
        type: "POST",
        data: form,
        async: true,        //异步
        processData: false,  //很重要，告诉jquery不要对form进行处理
        contentType: false,  //很重要，指定为false才能形成正确的Content-Type
        success: function (data) {
            console.log(i+1)
            var $audioFile = $("#audioFile");
            //显示上传状态
            var $text = $('[data-theme-name="upload-audio-text"]');
            $text.text(parseInt((100/shardCount*i)) + "%");
            uploadMultipart(i+1,file);
            //如果是最后一片则进行转码等工作
            if(i+1==shardCount){
                $text.text("上传成功，稍后开始转码");
                var status = data.status;
                if(status ==1){
                    part.audioUrl = data.data.path;

                    part.jobId = data.data.job.jobId;
                    var state = data.data.job.state;

                    //定时任务检查转码状态
                    part.intervalId = setInterval("getAudioJobProgress()", 2000);



                    //$('#audioFile').replaceWith($play);
                }
            }
        }
    });

//                }

}

/**
 * 获取音频转码进度
 */
function getAudioJobProgress(){
    $.ajax({
        url: "/vrs/api/checkAudio.jsn?jobId="+part.jobId,
        type: "GET",
        async: true,        //异步
        processData: false,  //很重要，告诉jquery不要对form进行处理
        contentType: false,  //很重要，指定为false才能形成正确的Content-Type
        success: function (data) {

            var status = data.status;
            if(status == 1){
                var state = data.data.state;
                //显示上传状态
                var $text = $('[data-theme-name="upload-audio-text"]');
                if(state == "TranscodeSuccess"){

                    clearInterval(part.intervalId);

                    //转码成功后获取播放地址
                    var playUrl = "http://audio.zhengzai.tv/"+data.data.output.outputFile.object;
                    var $audioFile = $("#audioFile");
                    var $urlInput = $audioFile.parent().find('[name="url"]');
                    $urlInput.val(playUrl);
                    console.log($urlInput.val());
                    var $play = $('#play');
                    $play.attr('src',playUrl);
                    $play.removeClass('hidden');

                    $text.text("转码成功");
                }

                if(state == "Submitted"){
                    $text.text("转码准备中。。。");
                }

                if(state == "Transcoding"){
                    $text.text("转码中。。。");
                }

            }
        }
    });

}
